import { ref } from 'vue'
import axios from '../plugins/axios'

export default (aid?: number) => {
   const form = ref<{ content: string; commontId?: number; replyUserId?: number }>({ content: '' })
   const createCommont = async () => {
      const res = await axios.request<CommontModel>({
         url: `commont/${aid}`,
         method: 'post',
         data: form.value
      })
      if (!res.data.commontId) {
         commontList.value?.push(res.data)
      } else {
         commontList.value?.map((item) => {
            if (item.id == res.data.commontId) {
               item.replys.push(res.data)
               return
            }
         })
      }
   }

   const commontList = ref<CommontModel[]>()
   const getAll = async () => {
      const res = await axios.request<CommontModel[]>({ url: `commont/${aid}` })
      commontList.value = res.data
   }

   const commont = ref<CommontModel>()
   const getOneCommont = async (cid: number) => {
      const res = await axios.request<CommontModel>({
         url: `commont/${aid}/${cid}`
      })
      commont.value = res.data
   }

   const deleteCommont = async (aid: number, id: number) => {
      const res = await axios.request<ArticelModel>({ url: `commont/${aid}/${id}`, method: 'Delete' })
      commontList.value?.map((item, index) => {
         if (item.id == res.data.id) commontList.value?.splice(index, 1)
      })
   }

   return {
      createCommont,
      commontList,
      getAll,
      form,
      deleteCommont,
      commont,
      getOneCommont
   }
}
